package netty.discard;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient {
    private int port;

    public TimeClient(int port) {
        this.port = port;
    }

    public void start() {
        EventLoopGroup work = new NioEventLoopGroup();//客户端只有一个工作线程池
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(work)
                    .channel(NioSocketChannel.class)//与server端不一样，NioSocketChannel客户端被创建时使用
                    .handler(new ChannelInitializer<SocketChannel>() {//配置一个新的 Channel
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new TimeDecoder(), new TimeClientHandler());
                        }
                    })
                    .option(ChannelOption.SO_KEEPALIVE, true);//设置这里指定的 Channel 实现的配置参数

            ChannelFuture future = bootstrap.connect("127.0.0.1", port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            work.shutdownGracefully();
        }


    }


    public static void main(String[] args) {
        new TimeClient(8080).start();
        //可以telnet连接测试一下
    }
}
